package com.km.wskj.itmonitor.pager.monitor.database.sqlserver;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Cpu;
import com.km.wskj.itmonitor.model.DBDetail;
import com.km.wskj.itmonitor.model.DataBase;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.Memory;
import com.km.wskj.itmonitor.model.SqlServerSize;
import com.km.wskj.itmonitor.model.SqlServerSizeList;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.AlarmListNoSpinnerActivity;
import com.km.wskj.itmonitor.pager.monitor.database.DBConfigActivity;
import com.km.wskj.itmonitor.pager.monitor.database.mysql.MySQLPerformActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerListActivity;
import com.km.wskj.itmonitor.utils.DynamicChartUtils;
import com.km.wskj.itmonitor.utils.FloatUtils;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class SQLServerDetailActivity extends LActivity {

    private static final String TAG = "SQLServerDetailActivity";
    //data
    private String ip;
    private String id;
    private DataBase mDataBase;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 在此处添加执行的代码
            initData();
            handler.postDelayed(this, 5000);// 5000ms后执行this，即runable
        }
    };

    //ui
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView mRightText;

    @BindView(R.id.tv_sqlserver_state)
    TextView mState;

    @BindView(R.id.tv_sqlserver_version)
    TextView mVersion;//数据库版本


    //chart
    @BindView(R.id.chart_db_cpu)
    LineChart mCpuChart;//cpu占用率
    @BindView(R.id.chart_db_physics)
    LineChart mPhyChart;//物理内存使用率
    @BindView(R.id.tv_sqlserver_cpu)
    TextView mCpu;//cpu
    @BindView(R.id.tv_sqlserver_physical_memory)
    TextView mPhy;//物理内存
    @BindView(R.id.tv_sqlserver_conversation)
    TextView mConversation;//会话数
    @BindView(R.id.tv_sqlserver_connections)
    TextView mConnections;//当前连接数
    @BindView(R.id.tv_sqlserver_memory)
    TextView mMemory;//实际内存占用
    @BindView(R.id.tv_sqlserver_deadlock)
    TextView mDeadlock;//数据库死锁
    @BindView(R.id.mysql_container_gridview)
    LinearLayout container_gridview;
    //饼图
    @BindView(R.id.sqlserver_pieChart1)
    PieChart mPieChart1;
    @BindView(R.id.sqlserver_pieChart2)
    PieChart mPieChart2;

    //data
    List<FuncItem> funcItems = new ArrayList<>();
    private MyGridView gridView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlserver_detail);
        ButterKnife.bind(this);
        if (getIntent().hasExtra("ip"))
            ip = getIntent().getStringExtra("ip");
        if (getIntent().hasExtra("id"))
            id = getIntent().getStringExtra("id");
        mDataBase = (DataBase) getIntent().getSerializableExtra("data");

        initData();
        initPie();
        handler.postDelayed(runnable, 5000);
        //初始化线性图
        DynamicChartUtils.initChart(mCpuChart, Color.parseColor("#ffffff"));
        DynamicChartUtils.initChart(mPhyChart, Color.parseColor("#ffffff"));


        initFuncItems();
        container_gridview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                container_gridview.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });

    }


    private void initData() {
        mBack.setVisibility(View.VISIBLE);
        mRightText.setVisibility(View.VISIBLE);
        mTitle.setText(mDataBase.databaseName + "数据库");
        mRightText.setText("报告");
        mVersion.setText(mDataBase.databaseVersion + "");

        initCpuPhy();
        initDbInfo();

    }

    /**
     * 饼图统计数据
     */
    private void initPie() {
        pdc.sqlserversize(HTTP_TASK_TAG, id, new ZxlGenericsCallback<SqlServerSize>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(SqlServerSize sqlServerSize, int i) {
                //目前先添加两个饼图
                ArrayList<PieEntry> entries1 = new ArrayList<PieEntry>();
                ArrayList<PieEntry> entries2 = new ArrayList<PieEntry>();

                SqlServerSizeList sizeList1 = sqlServerSize.serverSizeLists.get(0);
                SqlServerSizeList sizeList2 = sqlServerSize.serverSizeLists.get(1);

                entries1.add(new PieEntry(Float.parseFloat(sizeList1.value), "可用"));
                entries1.add(new PieEntry(Float.parseFloat(sizeList1.total) - Float.parseFloat(sizeList1.value), "已用"));

                entries2.add(new PieEntry(Float.parseFloat(sizeList2.value), "可用"));
                entries2.add(new PieEntry(Float.parseFloat(sizeList2.total) - Float.parseFloat(sizeList1.value), "已用"));


                initPieChart(mPieChart1, entries1, "", "总空间\n" + sizeList1.total + "MB");
                initPieChart(mPieChart2, entries2, "", "总空间\n" + sizeList2.total + "MB");


            }
        });


    }

    /**
     * 数据库信息
     */
    private void initDbInfo() {
        pdc.databaseDetail(HTTP_TASK_TAG, id, new ZxlGenericsCallback<DBDetail>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(DBDetail dbd, int i) {
                mConversation.setText(dbd.sessions + "");
                mConnections.setText(dbd.connections + "");
                mVersion.setText(dbd.version + "");
                mState.setText(dbd.instance + "\nACTIVE");
                mDeadlock.setText(dbd.lockMessage + "");
            }
        });

    }

    /**
     * 物理内存使用率和cpu使用率
     */

    private void initCpuPhy() {
        pdc.cpu(HTTP_TASK_TAG, ip, new ZxlGenericsCallback<Cpu>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Cpu cpu, int i) {
                if (cpu.total != null) {
                    mCpu.setText(cpu.total + "%");
                    DynamicChartUtils.addEntry(mCpuChart, Float.parseFloat(cpu.total));
                }
            }
        });

        pdc.memory(HTTP_TASK_TAG, ip, new ZxlGenericsCallback<Memory>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(Memory memory, int i) {
                float v = (Float.parseFloat(memory.usedPhysicsMem) / Float.parseFloat(memory.physicsMem));
                float v1 = FloatUtils.doubleFloat(v * 100);
                mPhy.setText(v1 + "%");
                DynamicChartUtils.addEntry(mPhyChart, v1);
            }
        });
    }

    //历史性能
    @OnClick(R.id.tool_bar_right_text)
    public void menu() {

    }

    //返回点击事件
    @OnClick(R.id.tool_bar_back)
    public void back() {
        finish();
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable);
        super.onDestroy();
    }


    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.mysql_func_title_array);
        String index[] = getResources().getStringArray(R.array.mysql_func_index);

        int r[] = {R.mipmap.lsxn_blue
                , R.mipmap.qt_blue
                , R.mipmap.db_blue
                , R.mipmap.config_blue
                , R.mipmap.alarm_blue
                , R.mipmap.jxsm_blue
                , R.mipmap.aqld_blue
                , R.mipmap.ccxx_blue
                , R.mipmap.gl_blue
                , R.mipmap.lsxn_blue
        };


        funcItems.clear();


        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            fi.index = index[i];
            funcItems.add(fi);
        }
    }


    private void createGridView() {

        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 4;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return container_gridview.getHeight() / 3;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return container_gridview.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getLayoutInflater().inflate(R.layout.monitor_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
                LinearLayout bg = (LinearLayout) view.findViewById(R.id.ll_minitor_bg);

                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return true;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //性能
                    case 0: {
                        Intent t = new Intent(context, SqlServerPerformActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //启停
                    case 1: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //备份
                    case 2: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //配置
                    case 3: {
                        Intent t = new Intent(context, DBConfigActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //报警
                    case 4: {
                        Intent t = new Intent(context, AlarmListNoSpinnerActivity.class);
                        t.putExtra("id", id);
                        startActivity(t);
                    }
                    break;
                    //基线扫描
                    case 5: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //安全漏洞
                    case 6: {
                        normalToasty("暂未开放功能");

                    }
                    break;
                    //服务器
                    case 7: {
                        openIntent(ServerListActivity.class, true);
                    }
                    break;
                    //关联
                    case 8: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //报告
                    case 9: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        container_gridview.addView(gridView.getView(), p);
    }


    /**
     * @param mPieChart 控件
     * @param entries   数据
     * @param str       比例图名称
     * @param centerStr 饼图中心标题
     */
    private void initPieChart(PieChart mPieChart, ArrayList<PieEntry> entries, String str, String centerStr) {
        //设置饼图是否使用百分比
        mPieChart.setUsePercentValues(true);
        //设置饼图右下角的文字描述
      /*  Description d = new Description();
        d.setText(str);
        mPieChart.setDescription(d);*/
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);

        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        //设置中间文件
        mPieChart.setCenterText(generateCenterSpannableText(centerStr));

        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);

        mPieChart.setHoleRadius(58f); //设置中间圆盘的半径,值为所占饼图的百分比
        mPieChart.setTransparentCircleRadius(61f);//设置中间透明圈的半径,值为所占饼图的百分比
        mPieChart.setDrawCenterText(true);


        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        //变化监听
//        mPieChart.setOnChartValueSelectedListener(this);

        //设置数据
        setData(entries, mPieChart, str);

        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置比例图
        Legend l = mPieChart.getLegend();
        l.setEnabled(false);//不要比例图
//        l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_INSIDE);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);//设置距离饼图的距离，防止与饼图重合
        l.setYEntrySpace(0f);
        l.setYOffset(0f);
        l.setForm(Legend.LegendForm.SQUARE);//设置比例块形状，默认为方块
        //        l.setEnabled(false);//设置禁用比例块
        //设置比例块换行...
//        l.setWordWrapEnabled(true);


        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(12f);
    }


    //设置中间文字
    private SpannableString generateCenterSpannableText(String str) {
        //原文：MPAndroidChart\ndeveloped by Philipp Jahoda
        SpannableString s = new SpannableString(str);
        //s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        //s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        // s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        //s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        // s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        // s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    //设置数据
    private void setData(ArrayList<PieEntry> entries, PieChart mPieChart, String str) {

        PieDataSet dataSet = new PieDataSet(entries, str);
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<>();

        /*for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());*/

        int[] MyColors = {
                Color.rgb(0, 238, 118), Color.rgb(100, 149, 237),
                Color.rgb(0, 191, 255), Color.rgb(255, 165, 0)
        };

        for (int c : MyColors)
            colors.add(c);


        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);

        //刷新
        mPieChart.invalidate();
    }


}
